//
//  LSContactsDetailViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/6/20.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSContactsDetailViewController.h"
#import "ContactModel.h"
#import "LSContactListTableViewCell.h"
#import <Contacts/Contacts.h>

@interface LSContactsDetailViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *tableViewHeaderView;
@property (nonatomic, strong) UILabel *nameLabel;
@end

static NSString *LSContactListTableViewCellID = @"LSContactListTableViewCellID";

@implementation LSContactsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"联系人";
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.tableViewHeaderView;
    
}

- (void)setModel:(ContactModel *)model {
    _model = model;
    self.nameLabel.text = [ValidateUtils validateNull:model.name];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSContactListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSContactListTableViewCellID forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.name = [ValidateUtils validateNull:_model.mobile];
        cell.phone = @"手机";
        cell.rightImageName = @"icon电话";
    } else if (indexPath.row == 1) {
        cell.name = [ValidateUtils validateNull:_model.department];
        cell.phone = @"部门";
        cell.rightImageName = @"icon部门";
    } else if (indexPath.row == 2) {
        cell.name = [ValidateUtils validateNull:_model.post];
        cell.phone = @"职务";
        cell.rightImageName = @"icon部门";
    } else {
        cell.name = @"添加到通讯录";
        cell.phone = @"";
        cell.rightImageName = @"icon保存号码";
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 60;
    } else if (indexPath.row == 1) {
        return 60;
    } else if (indexPath.row == 2) {
        return 60;
    } else {
        return 48;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if (indexPath.row == 0) {
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",_model.mobile]];
        UIWebView *webView = [[UIWebView alloc] init];
        [webView loadRequest:[NSURLRequest requestWithURL:url]];
        [self.view addSubview:webView];
    } else if (indexPath.row == 1) {
        // do nothing
    } else if (indexPath.row == 2) {
        // do nothing
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"确认添加到通讯录？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self registAuthorizeWithModel:self.model];
        }];
        [alertC addAction:cancelAction];
        [alertC addAction:confirmAction];
        [self presentViewController:alertC animated:true completion:nil];
    }
}

#pragma mark - 请求授权
-(void)registAuthorizeWithModel:(ContactModel *)model {
    CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (authorizationStatus == CNAuthorizationStatusNotDetermined) {
        //用户还没有决定是否授权
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"授权成功！");
                [self createCustomContactWithModel:model];
            } else {
                NSLog(@"授权失败, error=%@", error);
            }
        }];
    }else if (authorizationStatus == CNAuthorizationStatusAuthorized){
        //用户明确同意
        [self createCustomContactWithModel:model];
    }else{
        //用户明确拒绝或者程序中阻止了通讯录，可跳转通讯录手动打开
    }
}

#pragma mark - 获取数据
-(void)createCustomContactWithModel:(ContactModel *)model {
    CNMutableContact * contact = [[CNMutableContact alloc] init];
    if ([model.sex isEqualToString:@"女"]) {
        contact.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"famale"]);
    } else {
        contact.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"male"]);
    }
    //设置名字
    contact.givenName = model.name;
    contact.phoneNumbers = @[[CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberiPhone value:[CNPhoneNumber phoneNumberWithStringValue:model.mobile]]];
    //初始化方法
    CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
    //添加联系人
    [saveRequest addContact:contact toContainerWithIdentifier:nil];
    CNContactStore * store = [[CNContactStore alloc]init];
    NSError *error = nil;
    [store executeSaveRequest:saveRequest error:&error];
    if (error) {
        [MBProgressHUD showTipMessageInWindow:@"保存失败"];
        NSLog(@"保存失败--error:%@",error.localizedDescription);
    } else {
        [MBProgressHUD showTipMessageInWindow:@"保存成功"];
    }
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = hexColor(EEEEEE);
        [_tableView registerClass:LSContactListTableViewCell.class forCellReuseIdentifier:LSContactListTableViewCellID];
    }
    return _tableView;
}

- (UIImageView *)tableViewHeaderView {
    if (!_tableViewHeaderView) {
        _tableViewHeaderView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 900 * 649)];
        _tableViewHeaderView.image = [UIImage imageNamed:@"contactsDetailHeader"];
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, ScreenWidth / 900 * 649-35-35, ScreenWidth-70, 35)];
        nameLabel.textColor = hexColor(ffffff);
        nameLabel.textAlignment = NSTextAlignmentRight;
        nameLabel.text = [ValidateUtils validateNull:_model.name];
        nameLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:35];
        self.nameLabel = nameLabel;
        [_tableViewHeaderView addSubview:nameLabel];
    }
    return _tableViewHeaderView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
